<!-- create jishenghua-->
<template>
  <a-row :gutter="24">
    <a-col :md="24">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :md="6" :sm="24">
                <a-form-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入单据编号" v-model="queryParam.number"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="商品信息" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入条码、名称、规格、型号、颜色、扩展信息" v-model="queryParam.materialParam"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="单据日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-range-picker
                    style="width:100%"
                    v-model="queryParam.createTimeRange"
                    format="YYYY-MM-DD"
                    :placeholder="['开始时间', '结束时间']"
                    @change="onDateChange"
                    @ok="onDateOk"
                  />
                </a-form-item>
              </a-col>
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-col :md="6" :sm="24">
                  <a-button type="primary" @click="searchQuery">查询</a-button>
                  <a-button style="margin-left: 8px" @click="searchReset">重置</a-button>
                  <a @click="handleToggleSearch" style="margin-left: 8px">
                    {{ toggleSearchStatus ? '收起' : '展开' }}
                    <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                  </a>
                </a-col>
              </span>
              <template v-if="toggleSearchStatus">
                <a-col :md="6" :sm="24">
                  <a-form-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-select placeholder="选择客户" showSearch optionFilterProp="children" v-model="queryParam.organId">
                      <a-select-option v-for="(item,index) in cusList" :key="index" :value="item.id">
                        {{ item.supplier }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="操作员" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-select placeholder="选择操作员" showSearch optionFilterProp="children" v-model="queryParam.creator">
                      <a-select-option v-for="(item,index) in userList" :key="index" :value="item.id">
                        {{ item.userName }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="单据状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-select placeholder="选择单据状态" v-model="queryParam.status">
                      <a-select-option value="0">未审核</a-select-option>
                      <a-select-option value="1">已审核</a-select-option>
                      <a-select-option value="3">部分销售</a-select-option>
                      <a-select-option value="2">完成销售</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="单据备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input placeholder="请输入单据备注" v-model="queryParam.remark"></a-input>
                  </a-form-item>
                </a-col>
              </template>
            </a-row>
          </a-form>
        </div>
        <!-- 操作按钮区域 -->
        <div class="table-operator"  style="margin-top: 5px">
          <a-button v-if="btnEnableList.indexOf(1)>-1" @click="myHandleAdd(true)" type="primary" icon="plus">新增</a-button>
          <a-button v-if="btnEnableList.indexOf(1)>-1" @click="myHandleAdd(false)" type="primary" icon="plus">补单</a-button>
          <a-button @click="handleImportXls()" type="primary" icon="import">导入</a-button>
          <a-button @click="handleExportXSDD()" type="primary" icon="import">导出</a-button>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item key="1" v-if="btnEnableList.indexOf(1)>-1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
              <a-menu-item key="2" v-if="checkFlag && btnEnableList.indexOf(2)>-1" @click="batchSetStatus(1)"><a-icon type="check"/>审核</a-menu-item>
              <a-menu-item key="3" v-if="checkFlag && btnEnableList.indexOf(7)>-1" @click="batchSetStatus(0)"><a-icon type="stop"/>反审核</a-menu-item>
            </a-menu>
            <a-button>
              批量操作 <a-icon type="down" />
            </a-button>
          </a-dropdown>
          <a-tooltip placement="left" title="销售订单不涉及收款金额，销售订单可以转销售出库单，但需要先对销售订单进行审核。
          勾选单据之后可以进行批量操作（删除、审核、反审核）" slot="action">
            <a-icon v-if="btnEnableList.indexOf(1)>-1" type="question-circle" style="font-size:20px;float:right;" />
          </a-tooltip>
        </div>
        <!-- table区域-begin -->
        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :components="handleDrag(columns)"
            :pagination="false"
            :scroll="scroll"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">
            <span slot="action" slot-scope="text, record">
<!--              <div v-if="record.isChildren === '0'">-->
<!--                -->
<!--              </div>-->
              <a v-if="record.isChildren === '0'" @click="myHandleDetailEx(record)">查看</a>
              <a-divider v-if="btnEnableList.indexOf(1)>-1 && record.isChildren === '0'" type="vertical" />
              <a v-if="btnEnableList.indexOf(1)>-1 && record.isChildren === '0'" @click="myHandleEdit(record)">编辑</a>
              <a-divider v-if="btnEnableList.indexOf(1)>-1 && record.isChildren === '0'" type="vertical" />
              <!--<a v-if="btnEnableList.indexOf(1)>-1 && record.isChildren === '0'" @click="myHandleCopyAdd(record)">复制</a>
              <a-divider v-if="btnEnableList.indexOf(1)>-1 && record.isChildren === '0'" type="vertical" />-->
              <a-dropdown v-if="btnEnableList.indexOf(1)>-1 && record.isChildren === '0'">
                <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                  更多 <a-icon type="down" />
                </a>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a v-if="record.status !== '0' && record.rowIndex !== '合计'" @click="myHandleGotoOut(record)">跳转出库</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a @click="getLogList(record, 1)">查看审核记录</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a @click="getLogList(record, 0)">查看修改记录</a>
                  </a-menu-item>
                   <a-menu-item>
                    <a-popconfirm v-if="btnEnableList.indexOf(1)>-1 && record.isChildren === '0'" title="确定删除吗?" @confirm="() => myHandleDelete(record)">
                      <a>删除</a>
                    </a-popconfirm>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </span>
            <template slot="customRenderStatus" slot-scope="status">
              <a-tag v-if="status == '0'" color="red">未审核</a-tag>
              <a-tag v-if="status == '1'" color="green">已审核</a-tag>
              <a-tag v-if="status == '2'" color="cyan">完成销售</a-tag>
              <a-tag v-if="status == '3'" color="blue">部分发货</a-tag>
              <a-tag v-if="status == '4'" color="blue">已发货</a-tag>
              <a-tag v-if="status == '5'" color="orange">未发货</a-tag>
              <a-tag v-if="status == '9'" color="orange">审核中</a-tag>
            </template>
            <template slot="customRenderPurchaseStatus" slot-scope="purchaseStatus">
              <a-tag v-if="purchaseStatus == '0'" color="red">未采购</a-tag>
              <a-tag v-if="purchaseStatus == '2'" color="cyan">完成采购</a-tag>
              <a-tag v-if="purchaseStatus == '3'" color="blue">部分采购</a-tag>
            </template>
          </a-table>
          <a-row :gutter="24" style="margin-top: 8px;text-align:right;">
            <a-col :md="24" :sm="24">
              <a-pagination @change="paginationChange" @showSizeChange="paginationShowSizeChange"
                            size="small"
                            show-size-changer
                            :showQuickJumper="true"
                            :current="ipagination.current"
                            :page-size="ipagination.pageSize"
                            :page-size-options="ipagination.pageSizeOptions"
                            :total="ipagination.total"
                            :show-total="(total, range) => `共 ${total-Math.ceil(total/ipagination.pageSize)} 条`">
                <template slot="buildOptionText" slot-scope="props">
                  <span>{{ props.value-1 }}条/页</span>
                </template>
              </a-pagination>
            </a-col>
          </a-row>
        </div>
        <!-- table区域-end -->
        <!-- 表单区域 -->
        <sale-order-modal ref="modalForm" @ok="modalFormOk" @close="modalFormClose"></sale-order-modal>
        <bill-detail ref="modalDetail" @ok="modalFormOk" @close="modalFormClose"></bill-detail>
        <sale-order-print ref='print' :data-source='cols' :model='model'></sale-order-print>
        <import-file-modal ref="modalImportForm" @ok="modalFormOk"></import-file-modal>
        <a-modal :visible='exportVisible' ref='exportModal' @ok='exportModalOk' @cancel='exportModalClose'>
          <a-form>
            <a-form-item label="时间范围" >
              <a-range-picker
                style="width:100%"
                v-model="exportParam.createTimeRange"
                format="YYYY-MM-DD"
                :placeholder="['开始时间', '结束时间']"
                @change="onExportDateChange"
                @ok="onDateOk"
              />
            </a-form-item>
          </a-form>
        </a-modal>
        <a-modal v-model:visible="logVisible" :title="logTitle" width='1000px' :footer='null'>
          <a-table :dataSource="logDatasource" :columns="logColumns"  rowKey="id">
            <span slot="logAct" slot-scope="text, record">
              <a @click="logInfoCheck(record)">查看</a>
            </span>
          </a-table>
        </a-modal>
        <a-modal v-model:visible="logInfoVisible" title="详情" width='500px' :footer='null'>
          <a-list size="large" bordered :data-source="logInfoDatasource">
            <a-list-item slot="renderItem" slot-scope="item, index">
              {{ item }}
            </a-list-item>
        </a-list>
        </a-modal>
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
  import SaleOrderModal from './modules/SaleOrderModal'
  import ImportFileModal from '@comp/tools/ImportFileModal.vue'
  import BillDetail from './dialog/BillDetail'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { BillListMixin } from './mixins/BillListMixin'
  import { findBillDetailByNumber, getCurrentSystemConfig } from '@/api/api'
  import JDate from '@/components/jeecg/JDate'
  import Vue from 'vue'
  import { downFile, downloadFile, getAction } from '@api/manage'
  import SaleOrderPrint from '@views/bill/modules/SaleOrderPrintEx.vue'
  import { filterObj } from '@/utils/util'
  export default {
    name: "SaleOrderList",
    mixins:[JeecgListMixin,BillListMixin],
    components: {
      ImportFileModal,
      SaleOrderPrint,
      SaleOrderModal,
      BillDetail,
      JDate
    },
    data () {
      return {
        logDatasource: [],
        logTitle: "",
        logVisible: false,
        logInfoDatasource: [
          'Racing car sprays burning fuel into crowd.',
          'Japanese princess to wed commoner.',
          'Australian walks 100km after outback crash.',
          'Man charged over missing wedding girl.',
          'Los Angeles battles huge wildfires.',
        ],
        logInfoVisible: false,
        ipagination:{
          pageSize: 11,
          pageSizeOptions: ['11', '21', '31', '101', '501', '10001']
        },
        exportParam: {
          createTimeRange: []
        },
        exportVisible: false,
        // 查询条件
        queryParam: {
          number: "",
          materialParam: "",
          type: "其它",
          subType: "销售订单",
          roleType: Vue.ls.get('roleType'),
          organId: "",
          depotId: "",
          creator: "",
          status: "",
          remark: ""
        },
        prefixNo: 'XSDD',
        labelCol: {
          span: 5
        },
        wrapperCol: {
          span: 18,
          offset: 1
        },
        logColumns: [
          { title: '操作名称', dataIndex: 'operation',width:110, ellipsis:true},
          { title: '操作人员', dataIndex: 'userName',width:110, ellipsis:true},
          { title: '操作时间', dataIndex: 'createTime',width:110, ellipsis:true},
          {
            title: '操作',
            dataIndex: 'logAct',
            align:"center", width: 175,
            scopedSlots: { customRender: 'logAct' },
          },
        ],
        logInfoColumns: [
          { title: '', dataIndex: 'operation',width:110, ellipsis:true}
        ],
        // 表头
        columns: [
          {
            title: '#', dataIndex: 'rowIndex', width:40, align:"center",
            customRender:function (t,r,index) {
              return (t !== '合计') ? (parseInt(index) + 1) : t
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center", width: 175,
            scopedSlots: { customRender: 'action' },
          },
          { title: '客户', dataIndex: 'organName',width:110, ellipsis:true},
          { title: '单据编号', dataIndex: 'number',width:130},
          { title: '商品信息', dataIndex: 'materialsList',width:220, ellipsis:true,
            customRender:function (text,record,index) {
              if(text) {
                return text.replaceAll(",","，");
              }
            }
          },
          { title: '单据日期', dataIndex: 'operTimeStr',width:130},
          { title: '计划发货日期', dataIndex: 'sendDate',width:90},
          { title: '操作员', dataIndex: 'userName',width:80, ellipsis:true},
          { title: '数量', dataIndex: 'materialCount',width:50},
          { title: '金额合计', dataIndex: 'discountLastMoney',width:70},
          // { title: '含税合计', dataIndex: 'totalTaxLastMoney',width:80,
          //   customRender:function (text,record,index) {
          //     if(record.discountLastMoney) {
          //       return (record.discountMoney + record.discountLastMoney).toFixed(2);
          //     } else {
          //       return record.totalPrice;
          //     }
          //   }
          // },
          // { title: '收取订金', dataIndex: 'changeAmount',width:60},
          { title: '状态', dataIndex: 'status', width: 70, align: "center",
            scopedSlots: { customRender: 'customRenderStatus' }
          },
          { title: '采购进度', dataIndex: 'purchaseStatus', width: 70, align: "center",
            scopedSlots: { customRender: 'customRenderPurchaseStatus' }
          },
          {
            title: '是否子订单',
            dataIndex: 'isChildren',
            width:0,
            colSpan:0,
            customRender: (value, row, index) => {
              let obj = {
                children: value,
                attrs: {},
              };

              obj.attrs.colSpan = 0;
              return obj;
            }
          },
        ],
        model: {},
        cols: [],
        url: {
          list: "/depotHead/list",
          delete: "/depotHead/delete",
          deleteBatch: "/depotHead/deleteBatch",
          batchSetStatusUrl: "/depotHead/batchSetStatus",
          importExcelUrl: "/depotHead/importXSDDExcel",
          logUrl: "/sysLog/add"
        }
      }
    },
    created() {
      this.initSystemConfig()
      this.initCustomer()
      this.initUser()
      this.getSystemConfig()
    },
    computed: {
    },
    methods: {
      logInfoCheck(record) {
        this.logInfoVisible = true
        this.logInfoDatasource = record.content.split("\n")
        // console.log(this.logInfoDatasource)
      },
      getLogList(record, status) {
        getAction("/sysLog/list/" + record.id + "/" + status, {}).then(res => {
          if (res.code === 200) {
            if (status === 1) {
              this.logTitle = "查看审核记录"
            } else {
              this.logTitle = "查看修改记录"
            }
            this.logVisible = true
            this.logDatasource = res.data
          }
        })
      },
      myHandleAdd(readOnly) {
        this.$refs.modalForm.action = "add";
        this.$refs.modalForm.isReadOnly = readOnly
        if(this.btnEnableList.indexOf(2)===-1) {
          this.$refs.modalForm.isCanCheck = false
        }
        this.handleAdd();
      },
      onExportDateChange(value, dateString) {
        this.exportParam.beginTime=dateString[0] + " 00:00:00";
        this.exportParam.endTime=dateString[1] + " 23:59:59";
      },
      handleExportXSDD() {
        this.exportVisible = true
      },
      downLoadFiles(blobPart, filename) {
        const blob = new Blob([blobPart], { type: 'application/vnd.ms-excel' })
        console.log('downloadExcel', blob.size)
        // 创建一个超链接，将文件流赋进去，然后实现这个超链接的单击事件
        const elink = document.createElement('a')
        elink.download = decodeURIComponent(filename)
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      },
      exportModalOk() {
        downFile("/depotItem/exportXSDD", this.exportParam).then(res => {
          this.downLoadFiles(res, 'file.xlsx')
          this.exportModalClose()
        })
      },
      exportModalClose() {
        this.exportVisible = false
        this.exportParam = {
          createTimeRange: []
        }
      },
      handleImportXls() {
        let importExcelUrl = this.url.importExcelUrl
        let templateUrl = '/doc/xsdd_template.xlsx'
        let templateName = '订单导入Excel模板[下载]'
        this.$refs.modalImportForm.initModal(importExcelUrl, templateUrl, templateName);
        this.$refs.modalImportForm.title = "成品批量导入";
      },
      myHandleGotoOut(record) {
        let path = "/bill/sale_out?linkId=" + record.number
        this.dynamicRouterShow(path, 41, "销售出库", "/bill/SaleOutList");
      },
      getSystemConfig() {
        let statusIndex = 0
        for(let i=0; i<this.columns.length; i++){
          if(this.columns[i].dataIndex === 'purchaseStatus') {
            statusIndex = i
          }
        }
        getCurrentSystemConfig().then((res) => {
          if(res.code === 200 && res.data){
            let purchaseBySaleFlag = res.data.purchaseBySaleFlag
            if(purchaseBySaleFlag === "0") {
              if(statusIndex>0) {
                //移除采购进度列
                this.columns.splice(statusIndex, 1)
              }
            } else {
              if(statusIndex===0) {
                let purchaseStatusObj = { title: '采购进度', dataIndex: 'purchaseStatus', width: 70, align: "center",
                  scopedSlots: { customRender: 'customRenderPurchaseStatus' }
                }
                //添加采购进度列
                this.columns.splice(statusIndex-1, 0, purchaseStatusObj)
              }
            }
          } else {
            if(statusIndex>0) {
              //移除采购进度列
              this.columns.splice(statusIndex, 1)
            }
          }
        })
      },
      searchQuery() {
        this.loadData(1)
        this.getSystemConfig()
      },
      getQueryParams() {
        //获取查询条件
        let sqp = {}
        if(this.superQueryParams){
          sqp['superQueryParams']=encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        let searchObj = {}
        searchObj.search = JSON.stringify(this.queryParam);
        var param = Object.assign(sqp, searchObj, this.isorter ,this.filters);
        param.field = this.getQueryField();
        param.currentPage = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize - 1;
        return filterObj(param);
      },
      paginationChange(page, pageSize) {
        this.ipagination.current = page
        this.ipagination.pageSize = pageSize
        this.loadData(this.ipagination.current);
      },
      paginationShowSizeChange(current, size) {
        this.ipagination.current = current
        this.ipagination.pageSize = size
        this.loadData(this.ipagination.current);
      },
      myHandleDetailEx(record) {
        findBillDetailByNumber({number: record.number}).then(res => {
          this.model = res.data
          console.log(this.model)
          getAction('/depotItem/getDetailList', {
            headerId: record.id,
            mpList: '制造商,自定义1,自定义2,自定义3',
            linkType: 'basic'
          }).then(res => {
            this.cols = res.data.rows
            let totalCount = 0;
            for (let i = 0; i<this.cols.length; i++) {
              totalCount += Number(this.cols[i].operNumber)
            }
            this.cols.push({
              barCode: '合计',
              operNumber: totalCount,
              depotName: '',
              name: '',
              standard: '',
              unit: ''
            })
            this.$refs.print.visible = true
          })
        })
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>